package chapter17;

/**
 * @Auther: Tx
 * @Date: 2022/7/13 11:31
 */

//使用继承自Thread后，依旧会有超卖现象，应该将方法也加上static
public class SynThread {
    public static void main(String[] args) {
        SellTicket sellTicket = new SellTicket();
        new Thread(sellTicket).start();
        new Thread(sellTicket).start();
        new Thread(sellTicket).start();

    }

}

class SellTicket implements Runnable {
    private static int ticketCount = 100;

    private boolean isHaveTicket = true;

    private synchronized void sell() {
        if (ticketCount <= 0) {
            System.out.println("票已经售完");
            isHaveTicket = false;
            return;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "售出一张票" + "还剩" + (--ticketCount) + "张票");
    }

    @Override
    public void run() {
      while (isHaveTicket){
          sell();
      }
    }
}
